/**
 * Author: 老洋
 * Date:  2021/3/31 20:01
 */
package com.yyy.controller;

import com.yyy.dao.DepartmentDao;
import com.yyy.dao.EmployeeDao;
import com.yyy.pojo.Department;
import com.yyy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.selAllEmploy();
        model.addAttribute("employees", employees);
        return "/emp/list";
    }


    @GetMapping("/emp")
    public String addPage(Model model){
        Collection<Department> departments = departmentDao.getAllDepartmentsInfo();
        model.addAttribute("departments", departments);
        return "/emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee e){
        System.out.println("addEmp ==>> " + e);
        employeeDao.insEmploy(e);
        return "redirect:/emps";
    }

    @GetMapping("/upd/{id}")
    public String toUpd(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.selEmployById(id);
        model.addAttribute("employee", employee);

        Collection<Department> departments = departmentDao.getAllDepartmentsInfo();
        model.addAttribute("departments", departments);

        return "/emp/updPage";
    }

    @PostMapping("/updEnd")
    public String updEnd(Employee emp){
        emp.setDepartment(departmentDao.getDepartmentById(emp.getDepartment().getId()));

        System.out.println(emp);
        employeeDao.updEmploy(emp);

        return "redirect:/emps";
    }


    @GetMapping("/del")
        public String del(Integer id){
            employeeDao.delEmploy(id);
            System.out.println("del ===>>>" + id);
            return "redirect:/emps";
    }

    @GetMapping("/error")
    public String errorPage(){
        return "/error/404";
    }
}